<?php
namespace App\Admin\Controllers\Products;

use App\Admin\Actions\Products\SkuPacking\ImportSkuPacking;
use App\Admin\Extensions\Grid\Tool\Export;
use App\Models\Basics\PackingBox;
use App\Models\Product\ProductClassify;
use App\Models\Product\ProductMixSku;
use App\Models\Product\ProductPackingBox;
use App\Models\Product\ProductSku;
use App\Util\RExcel;
use App\Util\User;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\Request;

class SkuPackingBoxController extends AdminController{

    protected $title = '产品装箱规格';

    protected function grid()
    {
        $grid = new Grid(new ProductPackingBox());
        $grid->model()->newQuery()->orderBy('ID', 'DESC');
        $grid->model()->collection(function (Collection $collection){
            foreach($collection as $item) {
                $mix = $item->sku->is_mix ?? 0;
                if($mix == 1){
                    $re = ProductMixSku::getMixSkuPuCycleAndPuPriceAndNoTax($item->sku->mix_rule);
                    $item->unit_price = numberFormat($re['unit_price']);
                    $item->unit_price_no_tax = numberFormat($re['unit_price_no_tax']);
                    $item->purchase_cycle = numberFormat($re['purchase_cycle']);
                }else{
                    $item->unit_price = numberFormat($item->sku->product_supplier->unit_price ?? 0);
                    $item->unit_price_no_tax = numberFormat(ProductSku::tax($item->sku->product_supplier->unit_price ?? 0,$item->sku->product_supplier->supplier->tax ?? 0));
                    $item->purchase_cycle = numberFormat($item->sku->product_supplier->purchase_cycle ?? 0);
                }
                $item->muser_id = User::getUsernameById($item->muser_id);
            }
            return $collection;
        });
        $grid->column('packing_box.box_type','箱子类型');
        $grid->column('sku.psku_code','SKU');
        $grid->column('sku.psku_cn','名称')->style('max-width:200px');
        $grid->column('sku.classify_id','品类')->display(function ($value){
            return ProductClassify::getTitleById($value);
        });
        $grid->column('sku.is_mix','组合')->using(ProductSku::$_isMix)->style('width:45px');
        $grid->column('sku.mix_rule','组合规则')->style('max-width:200px');
        $grid->column('sku.is_sales','是否在售')->bool();

        $grid->column('unit_price','采购单价');
        $grid->column('unit_price_no_tax','不含税单价');
        $grid->column('purchase_cycle','采购周期');
        $grid->column('sku.psku_status','产品状态')->using(ProductSku::$_pSkuStatus)->hide();
        $grid->column('muser_id','负责人')->hide();
        $grid->column('sku.status','启用状态')->using(ProductSku::$_status);
        $grid->column('box_long','箱子长度(CM)');
        $grid->column('box_wide','箱子宽度(CM)');
        $grid->column('box_high','箱子高度(CM)');
        $grid->column('num_per_box','每箱发货数量');
        $grid->column('weight_per_box','每箱发货重量(KG)');
        if(Admin::user()->can('sku-packing.up') || Admin::user()->can('sku-packing.ship')){
            $grid->tools(function (Grid\Tools $tools) {
                $tools->append(new ImportSkuPacking());
            });
        }
        $grid->fixHeader();
        $grid->disableCreateButton();
        $grid->disableRowSelector();
        $grid->disableExport();
        $grid->tools(function (Grid\Tools $tools){
            $tools->append(new Export('products/sku-packing-box-download'));
        });
        $grid->disableActions();
        $grid->filter(function($filter){
            $filter->column(1/3, function ($filter){
                $filter->where(function ($query) {
                    $query->whereHas('sku', function ($query) {
                        $query->where('psku_code', 'like', "%{$this->input}%")
                            ->orWhere('psku_cn', 'like', "%{$this->input}%");
                    });
                }, '查询','sku8')->placeholder('模糊查询SKU，名称');
                $filter->equal('sku.classify_id', '品类')->select(ProductClassify::options());
                $filter->equal('packing_box_id', '箱类')->select(PackingBox::options());
            });
            $filter->column(1/3, function ($filter) {
                $filter->in('sku.psku_status', '状态')->checkbox(ProductSku::$_pSkuStatus);
                $filter->in('sku.is_mix', '组合')->checkbox(ProductSku::$_isMix);
            });
            $filter->column(1/3, function ($filter) {
                $filter->in('sku.status', '启用')->checkbox(ProductSku::$_status);
                $filter->in('sku.is_sales','在售')->checkbox(ProductSku::$_isSales);
            });
        });

        return $grid;
    }

    public function download(){
        $request = Request::input();
        $query = $this->_initQuery($request);
        $this->_exeDownload($query);
    }

    private function _initQuery($filters){
        $query = ProductPackingBox::query()->orderBy('id', 'DESC');
        foreach ($filters as $key => $_filter){
            if($key == 'sku8'){
                $query->whereHas('sku', function ($query) use($_filter){
                    $query->where('psku_code', 'like', "%{$_filter}%")
                        ->orWhere('psku_cn', 'like', "%{$_filter}%");
                });
            }
            if($key == 'sku'){
                $query->whereHas('sku', function ($query) use($_filter){
                    foreach ($_filter as $filed => $filter){
                        if(in_array($filed,['classify_id'])){
                            $query->where($filed, $filter);
                        }else{
                            $query->whereIn($filed, $filter);
                        }
                    }
                });
            }
        }
        return $query;
    }

    private function _exeDownload($query){
        $head = ['SKU','组合','组合规则','是否在售','名称','品类','采购单价','不含税单价','采购周期','产品状态','负责人','启用状态',
            '箱子类型','箱子长度(CM)','箱子宽度(CM)','箱子高度(CM)','每箱发货数量','每箱发货重量(KG)'];
        RExcel::exportCsv('产品装箱规格',function () use ($head, $query) {
            $fp = fopen('php://output', 'w');
            fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));
            fputcsv($fp, $head);
            $query->chunk(1000, function ($re) use ($fp){
                $data = self::getDownloadData($re);
                foreach ($data as $item) {
                    fputcsv($fp, $item);
                }
            });
        });
    }

    public static function getDownloadData($res)
    {
        $classify = [];
        $seller = [];
        foreach ($res as $model){
            $classifyId = $model->sku->classify_id ?? '';
            if(!array_key_exists($classifyId,$classify)){
                $classify[$classifyId] = ProductClassify::getTitleById($classifyId);
            }
            $sellerId = $model->sku->muser_id ?? 0;
            if(!array_key_exists($sellerId,$seller)){
                $seller[$sellerId] = User::getUsernameById($sellerId);
            }
            $mix = $model->sku->is_mix ?? 0;
            if($mix == 1){
                $data = ProductMixSku::getMixSkuPuCycleAndPuPriceAndNoTax($model->sku->mix_rule);
                $unitPrice = numberFormat($data['unit_price']);
                $unitPriceNoTax = numberFormat($data['unit_price_no_tax']);
                $purchaseCycle = numberFormat($data['purchase_cycle']);
            }else{
                $unitPrice = numberFormat($model->sku->product_supplier->unit_price ?? 0);
                $unitPriceNoTax = numberFormat(ProductSku::tax($model->sku->product_supplier->unit_price ?? 0,$model->sku->product_supplier->supplier->tax ?? 0));
                $purchaseCycle = numberFormat($model->sku->product_supplier->purchase_cycle ?? 0);
            }
            $temp = [
                $model->sku->psku_code ?? '',
                ProductSku::$_isMix[$mix],
                $model->sku->mix_rule ?? '',
                ProductSku::$_isSales[$model->sku->is_sales ?? 0],
                $model->sku->psku_cn ?? '',
                $classify[$classifyId],
                $unitPrice,
                $unitPriceNoTax,
                $purchaseCycle,
                isset($model->sku->psku_status)&&$model->sku->psku_status ? ProductSku::$_pSkuStatus[$model->sku->psku_status] : '',
                $seller[$sellerId],
                isset($model->sku->status)&&$model->sku->status ? ProductSku::$_status[$model->sku->status] : '',
                $model->packing_box->box_type ?? '',
                $model->box_long,
                $model->box_wide,
                $model->box_high,
                $model->num_per_box,
                $model->weight_per_box,
            ];
            yield $temp;
        }
    }
}
